package com.lanhao.aot.appender;

import java.util.Arrays;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;


/**
 * @author zurun
 * @date 2020/8/11 18:04:16
 */
public class MyAppender extends UnsynchronizedAppenderBase<LoggingEvent> {

    private final static Config config = ConfigService.getAppConfig();
    private final static String loggingLevelKey = "logging.level.com.iflytek.iot.platform";
    private final static String loggingLevelDefaultValue = "info,error";
    private final static String loggingLevelValue = config.getProperty(loggingLevelKey, loggingLevelDefaultValue).toUpperCase();

    @Override
    protected void append(LoggingEvent loggingEvent) {
        System.out.println("=====apollo 日志类型默认配置："+ loggingLevelValue +"=====");
//        LoggingEvent loggingEvent = (LoggingEvent) eventObject;
        System.out.println("===== loggingEvent 日志类型："+loggingEvent.getLevel().levelStr+"=====");
        LogModel logBean = new LogModel()
                .settName(loggingEvent.getThreadName())
                .setTimestamp(String.valueOf(loggingEvent.getTimeStamp()))
                .setLevel(loggingEvent.getLevel().levelStr)
                .setClassName(loggingEvent.getLoggerName())
                .setTraceId(loggingEvent.getMDCPropertyMap().get("traceId"))
                .setMessage(loggingEvent.getFormattedMessage());
        System.out.println("===== logBean 日志类型："+logBean.getLevel()+"=====");
        System.out.println(JSON.toJSONString(logBean));
        if (filter(logBean)) {
//            Log2kafkaQueue.add(logBean);
        	System.out.println("进入kafka日志采集");
        } else {
//            Log2kafkaQueue.incrementIgnore();
            System.out.println("忽略日志");
        }
        
        super.doAppend(loggingEvent);
    }

    /**
     * 丢弃flume日志。
     * 丢弃非${value}类型的日志
     * @param logBean logBean
     * @return true or false
     */
    private boolean filter(LogModel logBean) {
        String className = logBean.getClassName();
        if ("logcalLogger".equals(className) || "errLogger".equals(className)) {
            // flume日志丢弃
            return false;
        }
        System.out.println(Arrays.asList(loggingLevelValue));
        System.out.println(Arrays.asList(loggingLevelValue.toUpperCase().split(",")).contains(logBean.getLevel().toUpperCase()));
        return Arrays.asList(loggingLevelDefaultValue.toUpperCase().split(",")).contains("info".toUpperCase());
    }

}